package com.example.administrator.wallet.view.activity.mine.Personal.ChangNumber;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.BindMobileVarcodeBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.RelativeLayout.VerifyCodeView;
import com.example.administrator.wallet.view.activity.mine.Personal.PersonalCentreActivity;
import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import static com.example.administrator.wallet.R.id.et_new_number;
import static com.example.administrator.wallet.base.BaseActivity.context;


public class ChangNumberActivity extends AppCompatActivity {

    private ImageButton mIb_back;
    private TextView mV_title;
    private Button mBt_change;
    private EditText mEd_number;
    private View view;
    private RelativeLayout activity_chang_number;
    String mNumber = " ";
    private CharSequence temp;
    private BindMobileVarcodeBean bindMobileVarcodeBean;
    private int code = 0;
    final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    private String a = "123";
    private String str = "";
    private int con = 0;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chang_number);

        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        mBt_change = (Button) findViewById(R.id.bt_change);
        mEd_number = (EditText) findViewById(et_new_number);
        activity_chang_number = (RelativeLayout) findViewById(R.id.activity_chang_number);


        setStatuColor();
        Intent i = getIntent();
        a = i.getStringExtra("num");
        con = i.getIntExtra("context",0);
        if ("".equals(a)){
            mV_title.setText(R.string.bindingPhoneNumber);
            SharedPrefsUtil.putValue(ChangNumberActivity.this, "wallet", "changephone", getString(R.string.numfirstchange).toString());
//            initNotBind();
        }else{
            mV_title.setText(R.string.ModifyPhoneNumber);
            SharedPrefsUtil.putValue(ChangNumberActivity.this, "wallet", "changephone", getString(R.string.numchange).toString());
        }
        mIb_back.setVisibility(View.VISIBLE);


        mEd_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (temp.length() > 10) {
                    mBt_change.setEnabled(true);

                    mBt_change.setBackgroundDrawable(getResources().getDrawable(R.drawable.backups_button_selector));
                }else {
                    mBt_change.setEnabled(false);
                    mBt_change.setBackgroundDrawable(getResources().getDrawable(R.drawable.backups_button_normal));
                }
            }
        });


        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        mBt_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(temp.length() < 11){
                    Toast.makeText(getApplicationContext(), R.string.NumberJudge,Toast.LENGTH_SHORT).show();
                }else if(temp.length()  == 11 ){
                    mNumber = mEd_number.getText().toString();
                    initPw(mNumber);
                }
            }
        });

    }
    //跳转绑定手机号
    private void initNotBind() {
        view = View.inflate(ChangNumberActivity.this, R.layout.popup_binding_phone, null);
        final Button submit = (Button) view.findViewById(R.id.submit);
        final ImageView iv_close = (ImageView) view.findViewById(R.id.ib_close);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_chang_number, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(context, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(context, 1.0f);
                    }
                });
                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
                iv_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                        window.dismiss();
                    }
                });
            }
        });

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (con == 1){
            startActivity(new Intent(ChangNumberActivity.this,PersonalCentreActivity.class));
        }
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);

    }
    private void initPw(final String num) {
        final VerifyCodeView verifyCodeView;
        view = View.inflate(this, R.layout.popup_verification_number, null);
        final ImageButton submit = (ImageButton) view.findViewById(R.id.ib_verification_close);
        final Button not_received = (Button) view.findViewById(R.id.bt_not_received);
        final TextView tv_send_to = (TextView) view.findViewById(R.id.tv_send_to);
        final TimeButton obtain = (TimeButton) view.findViewById(R.id.bt_obtain);

        verifyCodeView = (VerifyCodeView) view.findViewById(R.id.bg_verfyCodeView);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_chang_number, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(ChangNumberActivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(ChangNumberActivity.this,1.0f);
                    }
                });


                obtain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reqequestManager.httpPost(Api.BaseUrl + Api.Get_Mobile_Varcode, Api.getGetMobileVarcode(SharedPrefsUtil.getValue(ChangNumberActivity.this,"wallet", "token",""),num), new IRequestCallback(){
                            @Override
                            public void onSuccess(String Response) {
                                Gson gson = new Gson();
                                bindMobileVarcodeBean = gson.fromJson(Response, BindMobileVarcodeBean.class);
                                code = bindMobileVarcodeBean.getCode();
                                if (code == 200){
                                    Log.e("tag","已请求验证码");
                                }
                            }
                            @Override
                            public void onFailure(String error) {
                                Toast.makeText(ChangNumberActivity.this, R.string.getcodeerr,Toast.LENGTH_LONG).show();
                            }
                        });

                    }
                });
                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
                not_received.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getApplicationContext(),NotReceivedActicity.class));
                    }
                });

                //验证码输入完成
                verifyCodeView.setInputCompleteListener(new VerifyCodeView.InputCompleteListener() {
                    @Override
                    public void inputComplete() {
                        reqequestManager.httpPost(Api.BaseUrl + Api.Bind_Mobile_Varcode, Api.getBindMobileVarcode(SharedPrefsUtil.getValue(ChangNumberActivity.this,"wallet", "token",""),num,verifyCodeView.getEditContent()), new IRequestCallback(){
                            @Override
                            public void onSuccess(String Response) {
                                Gson gson = new Gson();
                                bindMobileVarcodeBean = gson.fromJson(Response, BindMobileVarcodeBean.class);
                                code = bindMobileVarcodeBean.getCode();
                                if (code == 200){
                                    Log.e("tag","已收到验证码，验证手机号");
                                    str = SharedPrefsUtil.getValue(ChangNumberActivity.this, "wallet", "changephone", "");
                                    Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
                                    startActivity(new Intent(getApplicationContext(),PhoneNumberActivity.class));
                                    finish();
                                }else if(code == 501){
                                    Toast.makeText(getApplicationContext(), R.string.Authenticationerror,Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(getApplicationContext(),code +"",Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onFailure(String error) {
                                Toast.makeText(ChangNumberActivity.this,"获取验证码失败",Toast.LENGTH_LONG).show();
                            }
                        });
//                        Toast.makeText(ChangNumberActivity.this, "inputComplete: " + verifyCodeView.getEditContent(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void invalidContent() {

                    }
                });

                String str = getString(R.string.TheVerificationCodeHasBeenSent).toString();
                tv_send_to.setText( str +"\n"+ num);

            }
        });

    }



    protected void onDestroy() {
        // TODO Auto-generated method stub
//        v.onDestroy();
        super.onDestroy();
    }

    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }
    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
